/*
 * Copyright (c) 2017, Iotelligent Corporation
 * All rights reserved.
 *
 * Description:
 *
 *   delay functions(ms/us)
 *   use SysTick hw
 */


#include "iot_delay.h"
#include "stm32f4xx.h"
/*
 * tick: 24 bit
 * max system clk: 96M
 * tick count max time without overflow: 174.762ms
 *   16777215 = 0x00ffffff
 *   16777215/96 = 174.762ms
 *
 * us: < 174762
 */
static void delay_us_no_overflow( uint32_t us )
{
    uint32_t count;
    //count = ( system_clk / 1000000 ) * us;
    if( count == 0 )
    {
        return;
    }
    SysTick->LOAD = ( uint32_t )( count - 1UL );                /* set reload register */
    SysTick->VAL  = 0UL;                                        /* Load the SysTick Counter Value */
    SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk |
                    SysTick_CTRL_ENABLE_Msk;                    /* Enable SysTick IRQ and SysTick Timer */
    while( !( SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk ) );
}

/* Delay in us */
void delay_us( uint32_t us )
{
    uint32_t time_us, time_ms;
    time_ms = us / 1000;
    time_us = us % 1000;
    if( time_ms != 0 )
    {
        delay_ms( time_ms );
    }
    if( time_us != 0 )
    {
        delay_us_no_overflow( time_us );
    }
}

/* Delay in ms */
void delay_ms( uint32_t ms )
{
    uint32_t i;
    for( i = 0; i < ms; i++ )
    {
        delay_us_no_overflow( 1000 );
    }
}

